const app = getApp(), core = require('../../utils/core');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    city:[],
    search_list:[],
    keywords:''
  },
  // 清除全部历史
  clear_search:function(){
    wx.setStorageSync('home_search_list', []);
    this.setData({ search_list:[] })
  },
  // 输入搜索内容
  keywords:function(e){
    var keywords = e.detail.value;
    this.setData({ keywords: keywords })
  },
  // 搜索
  search:function(){
    var keywords = this.data.keywords;
    if (keywords.replace(/(^\s*)|(\s*$)/g, "") == ''){
      wx.showToast({
        title: '请输入要搜索的关键词',
        icon:'none'
      })
      return false;
    }
    this.save_search_list();
    wx.redirectTo({
      url: '/pages/search/search?talent='+this.data.talent+'&keywords='+keywords,
    })
  },

  // 保存搜索历史
  save_search_list: function (){
    var keywords = this.data.keywords;
    if(keywords == ''){
      wx.showToast({
        title: '请输入关键词',
        icon:'none'
      })
      return false;
    }
    var search_list = this.data.search_list;
    for(var i = 0; i < search_list.length; i++){
      if(search_list[i].name == keywords){
        return;
      }
    }
    search_list.push({ id:search_list.length+1, name:keywords });
    wx.setStorageSync('home_search_list', search_list);
  },
  // 点击搜索历史
  goto:function(e){
    var keywords = e.currentTarget.dataset.name;
    wx.redirectTo({
      url: '../search/search?talent='+this.data.talent+'&keywords=' + keywords,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({talent: options.talent||''});
    var search_list = wx.getStorageSync('home_search_list') || [];
    this.setData({ city: app.getCurrentCity(), search_list: search_list })
    app.eventBus.on(app.Events.CurrentCityChange, this.eventOnCurrentCityChange, this);
  },
  onUnload: function () {
    app.eventBus.off(app.Events.CurrentCityChange, this.eventOnCurrentCityChange);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.refreshOnShow) {
      this.setData({ refreshOnShow: false });
      this.refresh();
    }
  },
  eventOnCurrentCityChange: function (currentCity) {
    this.setData({ city: currentCity });
  }
});
